<?php
/**
 *
 * @since   2019-04-23
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace app\model;


use support\ThinkModel as Model;
use think\facade\Db;

class Base extends Model
{
    function get_hash_table($table, $userid)
    {
        $str = crc32($userid);
        if ($str < 0) {
            $hash = "0" . substr(abs($str), 0, 1);
        } else {
            $hash = substr($str, 0, 2);
        }
        return $table . "_" . $hash;
    }

    /**
     * 获取hash变量值
     * @param string $id
     * @return int
     */
    public function get_table_number($id = "")
    {
        $getTable = $this->getTable();
        $instance = new static;
        if (empty($id)) {
            $show_table = Db::query("show tables");
            $id_arr=[];
            if($show_table){
                foreach ($show_table as $key=>$value){
                    $table_name = $value['Tables_in_' . config('database.connections.mysql.database')];
                    if(strstr($getTable,$table_name)){
                        $id_arr[] = (integer)$instance->table($table_name)->max('id');
                    }
                }
            }
            $pos = array_search(max($id_arr), $id_arr);
            $id = $id_arr[$pos];
        }
        //每张表的数量
        $table_number = config('database.table_number');
        $hash = (integer)bcdiv($id, $table_number,2);
        return $hash;
    }


    /**
     * 设置表后缀
     * @param $suffix
     */
    public function setSuffix($suffix)
    {
        $table_number = config('database.table_number');
        $instance = new static;
        //判断表是否存在
        $is_table = Db::query("show tables");
        $data_table = array_filter(array_column($is_table, 'Tables_in_' . config('database.connections.mysql.database')));
        if ($suffix != 0) {
            //找上一张表的最大ID值
            if ($suffix == 1) {
                //$id = (integer)$instance->max('id');
                $id_max = $table_number + 1;
                if (in_array("{$this->getTable()}", $data_table)) {
                    $rs = Db::query("show COLUMNS FROM {$this->getTable()}");
                    $sql = "CREATE TABLE IF NOT EXISTS `{$this->table}{$suffix}` (";

                    if ($rs) {
                        foreach ($rs as $key => $value) {
                            $sql .= "`{$value['Field']}` {$value['Type']} NOT NULL {$value['Extra']},";
                        }
                    }
                    $sql .= "PRIMARY KEY (`id`)
) ENGINE=InnoDB  AUTO_INCREMENT=$id_max DEFAULT CHARSET=utf8";
                    Db::query($sql);
                }
                $this->suffix = $suffix;
            } elseif ($suffix > 1) {
                $_suffix = $suffix - 1;
                $new_id = $table_number * $_suffix;
                $id = (integer)$instance->table("{$this->table}{$_suffix}")->max('id');
                $id_max = $id + 1;
                if ($id < $new_id) {
                    $id_max = $new_id + 1;
                }
                if (in_array("{$this->table}{$_suffix}", $data_table)) {
                    $rs = Db::query("show COLUMNS from {$this->table}{$_suffix}");
                    if (!in_array("{$this->table}{$suffix}", $data_table)) {
                        $sql = "CREATE TABLE IF NOT EXISTS `{$this->table}{$suffix}` (";
                        if ($rs) {
                            foreach ($rs as $key => $value) {
                                $sql .= "`{$value['Field']}` {$value['Type']} NOT NULL {$value['Extra']},";
                            }
                        }
                        $sql .= "PRIMARY KEY (`id`)
) ENGINE=InnoDB  AUTO_INCREMENT=$id_max DEFAULT CHARSET=utf8";
                        Db::query($sql);
                    }
                }
                $this->suffix = $suffix;
            }
        }

    }

    /**
     * 提供一个静态方法设置表后缀(model调用静态方法才有作用)
     * @param string $suffix
     * @return \think\db\BaseQuery|\think\Model
     */
    public static function suffix($suffix)
    {
        $instance = new static;
        $instance->setSuffix($suffix);

        return $instance->newQuery();
    }

    /**
     * 获取总条数
     * @param $suffix
     * @param $where
     * @return int
     */
    public function totalNumberPages($suffix, $where)
    {
        $instance = new static;
        if ($suffix == 0) {
            $total = $instance->table("{$this->getTable()}")
                ->where(function ($q) use ($where) {
                    $q->where($where);
                })->count();
        } else {
            $total = 0;
            for ($i = 0; $i <= $suffix; $i++) {
                if ($i == 0) {
                    $total += $instance->table("{$this->getTable()}")
                        ->where(function ($q) use ($where) {
                            $q->where($where);
                        })->count();
                } else {
                    $total += $instance->table("{$this->table}{$suffix}")
                        ->where(function ($q) use ($where) {
                            $q->where($where);
                        })->count();
                }
            }
        }
        return $total;
    }

}
